#include "salestatistics.h"
#include "orderservice.h"
#include "appinitializer.h"
#include "saledao.h"
#include <QFont>
#include <QDate>
#include <QMessageBox>
#include <QDebug>
#include <QHeaderView>
#include <QSpacerItem>
#include <QFileDialog>
#include <QTextStream>
#include <QApplication>
#include <QStackedWidget>

SaleStatistics::SaleStatistics(const QMap<QString, QVariant> &userInfo, QWidget *parent)
    : QWidget(parent), m_currentUser(userInfo)
{
    // 初始化服务层
    Database *db = AppInitializer::database();
    m_orderService = new OrderService(this);
    m_saleDao = new SaleDAO(db);

    initUI();
    setupStyles();
    setupTable();
    loadProducts();
    loadData();

    // 连接信号槽
    connect(m_btnReturn, &QPushButton::clicked, this, &SaleStatistics::onReturnClicked);
    connect(m_btnRefresh, &QPushButton::clicked, this, &SaleStatistics::onRefreshClicked);
    connect(m_btnExport, &QPushButton::clicked, this, &SaleStatistics::onExportClicked);
    connect(m_btnSearch, &QPushButton::clicked, this, &SaleStatistics::onSearchClicked);
    connect(m_btnReset, &QPushButton::clicked, this, &SaleStatistics::onResetClicked);
    connect(m_cmbProduct, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &SaleStatistics::onProductChanged);
}

SaleStatistics::~SaleStatistics()
{
}

void SaleStatistics::initUI()
{
    // 创建主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(8, 8, 8, 8);
    m_mainLayout->setSpacing(8);

    // 创建顶部按钮和统计信息布局
    m_topButtonLayout = new QHBoxLayout();
    m_topButtonLayout->setSpacing(15);

    m_btnReturn = new QPushButton(tr("返回"), this);
    m_btnReturn->setObjectName("returnButton");
    m_btnReturn->setFixedSize(100, 40);

    // 创建统计信息标签（紧凑型）
    m_lblTotalRecords = new QLabel(tr("总记录数: 0"), this);
    m_lblTotalRecords->setObjectName("compactStatistics");
    
    m_lblTotalQuantity = new QLabel(tr("总销售数量: 0"), this);
    m_lblTotalQuantity->setObjectName("compactStatistics");
    
    m_lblTotalAmount = new QLabel(tr("总销售金额: ¥0.00"), this);
    m_lblTotalAmount->setObjectName("compactStatistics");
    
    m_lblAveragePrice = new QLabel(tr("平均单价: ¥0.00"), this);
    m_lblAveragePrice->setObjectName("compactStatistics");

    m_btnRefresh = new QPushButton(tr("刷新"), this);
    m_btnRefresh->setObjectName("refreshButton");
    m_btnRefresh->setFixedSize(100, 40);

    m_btnExport = new QPushButton(tr("导出"), this);
    m_btnExport->setObjectName("exportButton");
    m_btnExport->setFixedSize(100, 40);

    m_topButtonLayout->addWidget(m_btnReturn);
    m_topButtonLayout->addWidget(m_lblTotalRecords);
    m_topButtonLayout->addWidget(m_lblTotalQuantity);
    m_topButtonLayout->addWidget(m_lblTotalAmount);
    m_topButtonLayout->addWidget(m_lblAveragePrice);
    m_topButtonLayout->addStretch();
    m_topButtonLayout->addWidget(m_btnRefresh);
    m_topButtonLayout->addWidget(m_btnExport);

    m_mainLayout->addLayout(m_topButtonLayout, 0);

    // 创建滚动区域
    m_scrollArea = new QScrollArea(this);
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    m_contentWidget = new QWidget();
    m_contentLayout = new QVBoxLayout(m_contentWidget);
    m_contentLayout->setContentsMargins(5, 5, 5, 5);
    m_contentLayout->setSpacing(10);

    // 创建筛选区域
    m_filterGroup = new QGroupBox(tr("筛选条件"), m_contentWidget);
    m_filterGridLayout = new QGridLayout(m_filterGroup);
    m_filterGridLayout->setSpacing(15);
    m_filterGridLayout->setContentsMargins(20, 20, 20, 20);

    // 筛选控件
    m_lblStartDate = new QLabel(tr("开始日期:"), m_filterGroup);
    m_dateStart = new QDateEdit(QDate::currentDate().addDays(-30), m_filterGroup);
    m_dateStart->setCalendarPopup(true);
    m_dateStart->setDisplayFormat("yyyy-MM-dd");

    m_lblEndDate = new QLabel(tr("结束日期:"), m_filterGroup);
    m_dateEnd = new QDateEdit(QDate::currentDate(), m_filterGroup);
    m_dateEnd->setCalendarPopup(true);
    m_dateEnd->setDisplayFormat("yyyy-MM-dd");

    m_lblProduct = new QLabel(tr("商品:"), m_filterGroup);
    m_cmbProduct = new QComboBox(m_filterGroup);
    m_cmbProduct->setMinimumWidth(200);

    m_lblCustomer = new QLabel(tr("客户:"), m_filterGroup);
    m_edtCustomer = new QLineEdit(m_filterGroup);
    m_edtCustomer->setPlaceholderText(tr("输入客户名称"));

    m_btnSearch = new QPushButton(tr("查询"), m_filterGroup);
    m_btnSearch->setObjectName("searchButton");
    m_btnSearch->setFixedSize(80, 35);

    m_btnReset = new QPushButton(tr("重置"), m_filterGroup);
    m_btnReset->setObjectName("resetButton");
    m_btnReset->setFixedSize(80, 35);

    // 布局筛选控件
    m_filterGridLayout->addWidget(m_lblStartDate, 0, 0);
    m_filterGridLayout->addWidget(m_dateStart, 0, 1);
    m_filterGridLayout->addWidget(m_lblEndDate, 0, 2);
    m_filterGridLayout->addWidget(m_dateEnd, 0, 3);
    m_filterGridLayout->addWidget(m_btnSearch, 0, 4);
    m_filterGridLayout->addWidget(m_lblProduct, 1, 0);
    m_filterGridLayout->addWidget(m_cmbProduct, 1, 1);
    m_filterGridLayout->addWidget(m_lblCustomer, 1, 2);
    m_filterGridLayout->addWidget(m_edtCustomer, 1, 3);
    m_filterGridLayout->addWidget(m_btnReset, 1, 4);

    m_contentLayout->addWidget(m_filterGroup);

    // 创建数据表格
    m_tableWidget = new QTableWidget(m_contentWidget);
    m_contentLayout->addWidget(m_tableWidget, 1);

    m_scrollArea->setWidget(m_contentWidget);
    m_mainLayout->addWidget(m_scrollArea, 1);
}

void SaleStatistics::setupStyles()
{
    // 设置整体样式（绿色主题）
    this->setStyleSheet(
        "QWidget {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #f1f8e9, stop:1 #e8f5e8);"
        "    font-family: 'Microsoft YaHei', Arial, sans-serif;"
        "}"
        
        "QPushButton {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #4caf50, stop:1 #388e3c);"
        "    color: white;"
        "    border: none;"
        "    border-radius: 8px;"
        "    font-size: 14px;"
        "    font-weight: bold;"
        "    padding: 10px 20px;"
        "    min-height: 35px;"
        "}"
        
        "QPushButton:hover {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #66bb6a, stop:1 #4caf50);"
        "    border: 2px solid #388e3c;"
        "}"
        
        "QPushButton:pressed {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #388e3c, stop:1 #2e7d32);"
        "}"
        
        "#returnButton {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #e74c3c, stop:1 #c0392b);"
        "}"
        
        "#returnButton:hover {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #ec7063, stop:1 #e74c3c);"
        "}"
        
        "#searchButton, #resetButton {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #27ae60, stop:1 #229954);"
        "    font-size: 12px;"
        "    padding: 8px 15px;"
        "}"
        
        "#searchButton:hover, #resetButton:hover {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #58d68d, stop:1 #27ae60);"
        "}"
        
        "QGroupBox {"
        "    font-size: 14px;"
        "    font-weight: bold;"
        "    color: #2e7d32;"
        "    border: 2px solid #a5d6a7;"
        "    border-radius: 10px;"
        "    margin-top: 10px;"
        "    background: rgba(255, 255, 255, 0.8);"
        "}"
        
        "QGroupBox::title {"
        "    subcontrol-origin: margin;"
        "    left: 15px;"
        "    padding: 0 8px 0 8px;"
        "    background: #e8f5e8;"
        "    border-radius: 5px;"
        "}"
        
        "QLabel {"
        "    font-size: 13px;"
        "    color: #2e7d32;"
        "    font-weight: bold;"
        "}"
        
        "#compactStatistics {"
        "    font-size: 12px;"
        "    color: #34495e;"
        "    font-weight: bold;"
        "    background-color: rgba(255, 255, 255, 0.9);"
        "    border: 1px solid #bdc3c7;"
        "    border-radius: 6px;"
        "    padding: 8px 12px;"
        "    margin: 2px;"
        "    min-width: 120px;"
        "}"
        
        "QDateEdit, QComboBox, QLineEdit {"
        "    background: white;"
        "    border: 2px solid #a5d6a7;"
        "    border-radius: 6px;"
        "    padding: 8px;"
        "    font-size: 13px;"
        "    color: #2e7d32;"
        "}"
        
        "QDateEdit:focus, QComboBox:focus, QLineEdit:focus {"
        "    border-color: #4caf50;"
        "    border: 3px solid #4caf50;"
        "}"
        
        "QTableWidget {"
        "    background: white;"
        "    border: 1px solid #a5d6a7;"
        "    border-radius: 8px;"
        "    gridline-color: #e0e0e0;"
        "    font-size: 12px;"
        "    selection-background-color: #c8e6c9;"
        "}"
        
        "QTableWidget::item {"
        "    padding: 8px;"
        "    border-bottom: 1px solid #f0f0f0;"
        "}"
        
        "QTableWidget::item:selected {"
        "    background: #a5d6a7;"
        "    color: #2e7d32;"
        "}"
        
        "QHeaderView::section {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #66bb6a, stop:1 #4caf50);"
        "    color: white;"
        "    padding: 10px;"
        "    border: none;"
        "    font-weight: bold;"
        "    font-size: 13px;"
        "}"
        
        "QScrollArea {"
        "    border: none;"
        "    background: transparent;"
        "}"
        
        "QScrollBar:vertical {"
        "    background: #f5f5f5;"
        "    width: 12px;"
        "    border-radius: 6px;"
        "}"
        
        "QScrollBar::handle:vertical {"
        "    background: #a5d6a7;"
        "    border-radius: 6px;"
        "    min-height: 20px;"
        "}"
        
        "QScrollBar::handle:vertical:hover {"
        "    background: #81c784;"
        "}"
    );
}

void SaleStatistics::setupTable()
{
    // 设置表格列
    QStringList headers;
    headers << tr("订单号") << tr("销售日期") << tr("商品名称") << tr("商品编码")
            << tr("销售数量") << tr("单价") << tr("总金额") << tr("客户名称")
            << tr("收银员") << tr("支付方式") << tr("订单状态");
    
    m_tableWidget->setColumnCount(headers.size());
    m_tableWidget->setHorizontalHeaderLabels(headers);
    
    // 设置表格属性
    m_tableWidget->setAlternatingRowColors(true);
    m_tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    m_tableWidget->setSortingEnabled(true);
    m_tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    
    // 设置列宽
    QHeaderView *header = m_tableWidget->horizontalHeader();
    header->setStretchLastSection(true);
    header->resizeSection(0, 120); // 订单号
    header->resizeSection(1, 100); // 销售日期
    header->resizeSection(2, 150); // 商品名称
    header->resizeSection(3, 100); // 商品编码
    header->resizeSection(4, 80);  // 销售数量
    header->resizeSection(5, 80);  // 单价
    header->resizeSection(6, 100); // 总金额
    header->resizeSection(7, 120); // 客户名称
    header->resizeSection(8, 80);  // 收银员
    header->resizeSection(9, 80);  // 支付方式
    header->resizeSection(10, 80); // 订单状态
}

void SaleStatistics::loadData()
{
    if (!m_saleDao) {
        qDebug() << "SaleDAO未初始化";
        return;
    }

    // 获取所有销售记录
    QVector<QMap<QString, QVariant>> records = m_saleDao->getAllSaleRecords();
    
    // 清空现有记录
    m_allRecords.clear();
    
    // 转换数据格式
    for (const auto &record : records) {
        QMap<QString, QVariant> saleRecord;
        saleRecord["order_id"] = record["order_id"];
        saleRecord["sale_date"] = record["sale_date"];
        saleRecord["product_name"] = record["product_name"];
        saleRecord["product_code"] = record["product_id"]; // 使用product_id作为商品编码
        saleRecord["quantity"] = record["quantity"];
        saleRecord["unit_price"] = record["unit_price"];
        saleRecord["total_amount"] = record["total_amount"];
        saleRecord["customer_name"] = record["customer_name"];
        saleRecord["cashier"] = record["cashier"];
        saleRecord["payment_method"] = record["payment_method"];
        saleRecord["order_status"] = record["order_status"];
        m_allRecords.append(saleRecord);
    }
    
    m_filteredRecords = m_allRecords;
    updateTable();
    updateStatistics();
    
    qDebug() << "销售统计数据加载完成，共" << m_allRecords.size() << "条记录";
}

void SaleStatistics::loadProducts()
{
    m_cmbProduct->clear();
    m_cmbProduct->addItem(tr("全部商品"), "");
    
    // TODO: 从数据库加载商品列表
    // 示例数据
    m_cmbProduct->addItem("可口可乐", "P001");
    m_cmbProduct->addItem("百事可乐", "P002");
    m_cmbProduct->addItem("雪碧", "P003");
}

void SaleStatistics::filterData()
{
    if (!m_saleDao) {
        qDebug() << "SaleDAO未初始化";
        return;
    }

    // 获取筛选条件
    QString startDate = m_dateStart->date().toString("yyyy-MM-dd");
    QString endDate = m_dateEnd->date().toString("yyyy-MM-dd");
    QString productCode = m_cmbProduct->currentData().toString();
    QString customerName = m_edtCustomer->text().trimmed();
    
    // 根据条件查询数据
    int productId = productCode.isEmpty() ? -1 : productCode.toInt();
    int customerId = customerName.isEmpty() ? -1 : customerName.toInt();
    QVector<QMap<QString, QVariant>> records = m_saleDao->getSaleRecordsByCondition(
        startDate, endDate, productId, customerId);
    
    // 清空筛选结果
    m_filteredRecords.clear();
    
    // 转换数据格式
    for (const auto &record : records) {
        QMap<QString, QVariant> saleRecord;
        saleRecord["order_id"] = record["order_id"];
        saleRecord["sale_date"] = record["sale_date"];
        saleRecord["product_name"] = record["product_name"];
        saleRecord["product_code"] = record["product_id"]; // 使用product_id作为商品编码
        saleRecord["quantity"] = record["quantity"];
        saleRecord["unit_price"] = record["unit_price"];
        saleRecord["total_amount"] = record["total_amount"];
        saleRecord["customer_name"] = record["customer_name"];
        saleRecord["cashier"] = record["cashier"];
        saleRecord["payment_method"] = record["payment_method"];
        saleRecord["order_status"] = record["order_status"];
        m_filteredRecords.append(saleRecord);
    }
    
    updateTable();
    updateStatistics();
    
    qDebug() << "销售数据筛选完成，共" << m_filteredRecords.size() << "条记录";
}

void SaleStatistics::updateTable()
{
    m_tableWidget->setRowCount(m_filteredRecords.size());
    
    for (int i = 0; i < m_filteredRecords.size(); ++i) {
        const auto &record = m_filteredRecords[i];
        
        m_tableWidget->setItem(i, 0, new QTableWidgetItem(record["order_id"].toString()));
        m_tableWidget->setItem(i, 1, new QTableWidgetItem(record["sale_date"].toDate().toString("yyyy-MM-dd")));
        m_tableWidget->setItem(i, 2, new QTableWidgetItem(record["product_name"].toString()));
        m_tableWidget->setItem(i, 3, new QTableWidgetItem(record["product_code"].toString()));
        m_tableWidget->setItem(i, 4, new QTableWidgetItem(QString::number(record["quantity"].toInt())));
        m_tableWidget->setItem(i, 5, new QTableWidgetItem(QString("¥%1").arg(record["unit_price"].toDouble(), 0, 'f', 2)));
        m_tableWidget->setItem(i, 6, new QTableWidgetItem(QString("¥%1").arg(record["total_amount"].toDouble(), 0, 'f', 2)));
        m_tableWidget->setItem(i, 7, new QTableWidgetItem(record["customer_name"].toString()));
        m_tableWidget->setItem(i, 8, new QTableWidgetItem(record["cashier"].toString()));
        m_tableWidget->setItem(i, 9, new QTableWidgetItem(record["payment_method"].toString()));
        m_tableWidget->setItem(i, 10, new QTableWidgetItem(record["order_status"].toString()));
    }
}

void SaleStatistics::updateStatistics()
{
    int totalRecords = m_filteredRecords.size();
    int totalQuantity = 0;
    double totalAmount = 0.0;
    
    for (const auto &record : m_filteredRecords) {
        totalQuantity += record["quantity"].toInt();
        totalAmount += record["total_amount"].toDouble();
    }
    
    double averagePrice = (totalQuantity > 0) ? (totalAmount / totalQuantity) : 0.0;
    
    m_lblTotalRecords->setText(QString("总记录数: %1").arg(totalRecords));
    m_lblTotalQuantity->setText(QString("总销售数量: %1").arg(totalQuantity));
    m_lblTotalAmount->setText(QString("总销售金额: ¥%1").arg(totalAmount, 0, 'f', 2));
    m_lblAveragePrice->setText(QString("平均单价: ¥%1").arg(averagePrice, 0, 'f', 2));
}

void SaleStatistics::clearFilters()
{
    m_dateStart->setDate(QDate::currentDate().addDays(-30));
    m_dateEnd->setDate(QDate::currentDate());
    m_cmbProduct->setCurrentIndex(0);
    m_edtCustomer->clear();
    
    m_filteredRecords = m_allRecords;
    updateTable();
    updateStatistics();
}

// 槽函数实现
void SaleStatistics::onReturnClicked()
{
    // 返回到上一级界面
    QWidget *parent = this->parentWidget();
    if (parent) {
        QStackedWidget *stackedWidget = qobject_cast<QStackedWidget*>(parent);
        if (stackedWidget && stackedWidget->currentIndex() > 0) {
            stackedWidget->setCurrentIndex(0); // 返回到第一个页面
        }
    }
}

void SaleStatistics::onRefreshClicked()
{
    loadData();
    QMessageBox::information(this, tr("提示"), tr("数据已刷新"));
}

void SaleStatistics::onSearchClicked()
{
    filterData();
}

void SaleStatistics::onResetClicked()
{
    clearFilters();
}

void SaleStatistics::onExportClicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("导出销售统计"), 
                                                   QString("销售统计_%1.csv").arg(QDate::currentDate().toString("yyyyMMdd")),
                                                   tr("CSV文件 (*.csv)"));
    
    if (!fileName.isEmpty()) {
        QFile file(fileName);
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QTextStream out(&file);
            out.setCodec("UTF-8");
            
            // 写入表头
            out << "订单号,销售日期,商品名称,商品编码,销售数量,单价,总金额,客户名称,收银员,支付方式,订单状态\n";
            
            // 写入数据
            for (const auto &record : m_filteredRecords) {
                out << record["order_id"].toString() << ","
                    << record["sale_date"].toDate().toString("yyyy-MM-dd") << ","
                    << record["product_name"].toString() << ","
                    << record["product_code"].toString() << ","
                    << record["quantity"].toInt() << ","
                    << record["unit_price"].toDouble() << ","
                    << record["total_amount"].toDouble() << ","
                    << record["customer_name"].toString() << ","
                    << record["cashier"].toString() << ","
                    << record["payment_method"].toString() << ","
                    << record["order_status"].toString() << "\n";
            }
            
            file.close();
            QMessageBox::information(this, tr("导出成功"), tr("销售统计已导出到: %1").arg(fileName));
        } else {
            QMessageBox::warning(this, tr("导出失败"), tr("无法创建文件: %1").arg(fileName));
        }
    }
}

void SaleStatistics::onProductChanged(int index)
{
    Q_UNUSED(index)
    // 商品选择改变时可以触发自动筛选
    // filterData();
}